/*
 * @Author: wei_jt@ecidi.com
 * @Date: 2021-09-24 11:36:19
 * @LastEditors: wei_jt@ecidi.com
 * @LastEditTime: 2021-12-30 14:01:33
 * @Description: file content
 */
import fileTypeIcon from '@/config/fileIcon'
//常用文本
export const download = (file, blobs) => {
  let blob = new File([blobs], { type: 'application/octet-stream' })
  if ('download' in document.createElement('a')) {
    const downloadElement = document.createElement('a')
    let href = ''
    if (window.URL) {
      href = window.URL.createObjectURL(blob)
    } else {
      href = window.webkitURL.createObjectURL(blob)
    }
    downloadElement.href = href
    downloadElement.download = file.fileName || file.name
    document.body.appendChild(downloadElement)
    downloadElement.click()
    if (window.URL) {
      window.URL.revokeObjectURL(href)
    } else {
      window.webkitURL.revokeObjectURL(href)
    }
    document.body.removeChild(downloadElement)
    URL.revokeObjectURL(href) //释放 Blob
  } else {
    navigator.msSaveBlob(blob, file.fileName || file.name)
  }
  return
}

//excel
export function exportFile (response) {
  const blob = new Blob([response.data], { type: response.headers['content-type'] }) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  const desprsitions = (response.headers['content-disposition'] || '').split(';')
  let filename = ''
  for (let i = 0; i < desprsitions.length; i++) {
    if (desprsitions[i].indexOf('filename') > -1) {
      const filenames = desprsitions[i].split('=')
      if (filenames.length > 1) {
        filename = decodeURI(filenames[1].trim())
      }
    }
  }
  if ('download' in document.createElement('a')) {
    const downloadElement = document.createElement('a')
    let href = ''
    if (window.URL) {
      href = window.URL.createObjectURL(blob)
    } else {
      href = window.webkitURL.createObjectURL(blob)
    }
    downloadElement.href = href
    downloadElement.download = filename
    document.body.appendChild(downloadElement)
    downloadElement.click()
    if (window.URL) {
      window.URL.revokeObjectURL(href)
    } else {
      window.webkitURL.revokeObjectURL(href)
    }
    document.body.removeChild(downloadElement)
  } else {
    navigator.msSaveBlob(blob, filename)
  }
}

export function getFileIconByExtName (extName) {
  if (fileTypeIcon[extName]) {
    return fileTypeIcon[extName]
  }

  return 'doc_blank'
}